package com.gr.dmbackend.service.Impl.student;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.dmbackend.mapper.DormitoryMapper;
import com.gr.dmbackend.mapper.RepairMapper;
import com.gr.dmbackend.mapper.StudentMapper;
import com.gr.dmbackend.model.Repair;
import com.gr.dmbackend.model.Student;
import com.gr.dmbackend.service.student.AddRepairService;
import com.gr.dmbackend.utils.GetUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class AddRepairServiceImpl implements AddRepairService {

    @Autowired
    private RepairMapper repairMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public JSONObject addRepair(Map<String, String> data) {

        JSONObject resp = new JSONObject();

        String repairType = data.get("repairType");
        String repairItem = data.get("repairItem");
        String repairReason = data.get("repairReason");

        if ("请选择报修种类".equals(repairType)) {
            resp.put("error_message", "请选择报修种类");
            return resp;
        }
        if ("请选择报修项目".equals(repairItem)) {
            resp.put("error_message", "请选择报修项目");
            return resp;
        }
        if (repairReason.isEmpty()) {
            resp.put("error_message", "报修原因不能为空");
            return resp;
        }
        if (repairType.length() > 20) {
            resp.put("error_message", "报修种类长度超出限制");
            return resp;
        }
        if (repairItem.length() > 20) {
            resp.put("error_message", "报修项目长度超出限制");
            return resp;
        }
        if (repairReason.length() > 10) {
            resp.put("error_message", "报修原因长度超出限制");
            return resp;
        }

        QueryWrapper<Student> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("student_id", GetUserUtil.getCurrentUser().getUsername());
        Student student = studentMapper.selectOne(queryWrapper1);
        if (student == null) {
            resp.put("error_message", "当前学生不存在");
            return resp;
        }

        Repair repair = new Repair();
        repair.setStudentId(student.getStudentId());
        repair.setName(student.getName());
        repair.setBuilding(student.getBuilding());
        repair.setDormId(student.getDormId());
        repair.setRepairType(repairType);
        repair.setRepairItem(repairItem);
        repair.setRepairReason(repairReason);
        repairMapper.insert(repair);
        resp.put("error_message", "success");

        return resp;
    }
}
